package cn.cdm.service;


import cn.cdm.dao.RedDetailMapper;
import cn.cdm.dao.RedRecordMapper;
import cn.cdm.dao.RedRobRecordMapper;
import cn.cdm.entity.po.RedDetail;
import cn.cdm.entity.po.RedRecord;
import cn.cdm.entity.po.RedRobRecord;
import cn.cdm.entity.dto.RedPacketDto;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.scheduling.annotation.Async;
import org.springframework.scheduling.annotation.EnableAsync;
import org.springframework.stereotype.Service;
import org.springframework.transaction.annotation.Transactional;

import java.math.BigDecimal;
import java.util.Date;
import java.util.List;

/**
 * @author: zhonglinsen
 * @date: 2019/3/18
 */
@Slf4j
@Service
@EnableAsync
public class RedService {

    @Autowired
    private RedRecordMapper redRecordMapper;

    @Autowired
    private RedDetailMapper redDetailMapper;

    @Autowired
    private RedRobRecordMapper redRobRecordMapper;

    /**
     * 发红包记录
     * 注意事项：@Transactional 事务的含义，当事务注解在方法上时，必须是该方法全部执行完成，才会去提交事务。也就是执行完该方法后，一次性提交该事务
     * 若该方法上没有该事务注解，for循环中，每次执行redDetailMapper.insertSelective(detail);方法，会提交一次事务，会提交10次事务。
     * @param dto
     * @param redId
     * @param list
     * @throws Exception
     */
//    @Async
    @Transactional(rollbackFor = Exception.class)  // 注意事项：@Transactional 事务的含义
    public void recordRedPacket(RedPacketDto dto, String redId, List<Integer> list) {
        log.info("打印3：recordRedPacket方法：{}", redId);
        // 将红包总个数存入数据库
        RedRecord redRecord=new RedRecord();
        redRecord.setUserId(dto.getUserId());
        redRecord.setRedPacket(redId);
        redRecord.setTotal(dto.getTotal());
        redRecord.setAmount(BigDecimal.valueOf(dto.getAmount()));
        redRecord.setCreateTime(new Date());
        // 新增之后返回新增行的主键ID，由于主键是自增的，所以实现方法需要在xml中配置useGeneratedKeys以及keyProperty这两个属性
        redRecordMapper.insertSelective(redRecord);

        // 将每个红包的详细信息、随机金额，存入数据库
        RedDetail detail;
        for (Integer i:list){
            detail=new RedDetail();
            // 获取红包记录表的主键id，存入红包随机金额表中，record_id字段的取值对应red_record表的主键字段取值
            detail.setRecordId(redRecord.getId());
            detail.setAmount(BigDecimal.valueOf(i));
            detail.setCreateTime(new Date());
            redDetailMapper.insertSelective(detail);
        }
    }

    /**
     * 抢红包记录
     * @param userId
     * @param redId
     * @param amount
     * @throws Exception
     */
//    @Async
    @Transactional
    public void recordRobRedPacket(Integer userId, String redId, BigDecimal amount) throws Exception {
        RedRobRecord redRobRecord=new RedRobRecord();
        redRobRecord.setUserId(userId);
        redRobRecord.setRedPacket(redId);
        redRobRecord.setAmount(amount);
        redRobRecord.setRobTime(new Date());
        redRobRecordMapper.insertSelective(redRobRecord);
    }
}









































